package nettcp;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class J_TCPServer {
    public static void main(String[] args) {
        ServerSocket server = null;
        try {
            server = new ServerSocket(8000);
            while (true){
                //等待并监听来自客户端的连接
                Socket socket = server.accept();
                String string = "";
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                while (!"exit".equals(string = dataInputStream.readUTF())){
                    System.out.println("Accept the client connection,message:"+string);
                    dataOutputStream.writeUTF("Server is ok");
                    dataOutputStream.flush();
                }

                dataInputStream.close();
                dataOutputStream.close();
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (server != null) {
                    server.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
